import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { 
  User, 
  Lock, 
  Eye,
  EyeOff, 
  LogIn,
  UserPlus,
  Loader2
} from 'lucide-react';
import { userApi } from '@/services/api';
import { useToast } from '@/hooks/use-toast';

interface LoginFormProps {
  onLoginSuccess: (user: any) => void;
}

export function LoginForm({ onLoginSuccess }: LoginFormProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { toast } = useToast();

  // 登录表单状态
  const [loginForm, setLoginForm] = useState({
    userAccount: '',
    userPassword: '',
  });

  // 注册表单状态
  const [registerForm, setRegisterForm] = useState({
    userAccount: '',
    userPassword: '',
    checkPassword: '',
  });

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    
    if (!loginForm.userAccount || !loginForm.userPassword) {
      setError('请填写完整的登录信息');
      return;
    }

    setLoading(true);
    try {
      const response = await userApi.login(loginForm);
      
      if (response.code === 0) {
        // 保存token到localStorage
        if (response.data.token) {
          localStorage.setItem('token', response.data.token);
        }
        
        toast({
          title: "登录成功",
          description: `欢迎回来，${response.data.userName || '用户'}！`,
        });
        
        onLoginSuccess(response.data);
      } else {
        setError(response.message || '登录失败');
      }
    } catch (error: any) {
      setError(error.response?.data?.message || '登录失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    
    if (!registerForm.userAccount || !registerForm.userPassword || !registerForm.checkPassword) {
      setError('请填写完整的注册信息');
      return;
    }

    if (registerForm.userPassword !== registerForm.checkPassword) {
      setError('两次输入的密码不一致');
      return;
    }

    if (registerForm.userPassword.length < 6) {
      setError('密码长度至少6位');
      return;
    }

    setLoading(true);
    try {
      const response = await userApi.register(registerForm);
      
      if (response.code === 0) {
        toast({
          title: "注册成功",
          description: "请使用新账户登录",
        });
        
        // 清空注册表单，切换到登录标签
        setRegisterForm({
          userAccount: '',
          userPassword: '',
          checkPassword: '',
        });
        
        // 自动填充登录表单
        setLoginForm({
          userAccount: registerForm.userAccount,
          userPassword: '',
        });
      } else {
        setError(response.message || '注册失败');
      }
    } catch (error: any) {
      setError(error.response?.data?.message || '注册失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 via-white to-cyan-50 p-4">
      <div className="w-full max-w-md">
        {/* Logo和标题 */}
        <div className="text-center mb-8">
          <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-cyan-600 rounded-full mb-4">
            <User className="h-8 w-8 text-white" />
          </div>
          <h1 className="text-3xl font-bold bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent">
            智能BI平台
          </h1>
          <p className="text-gray-600 mt-2">数据驱动，智能分析</p>
        </div>

        <Card className="shadow-2xl border-0 bg-white/80 backdrop-blur-sm">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-2xl text-gray-800">欢迎使用</CardTitle>
          </CardHeader>
          <CardContent>
            <Tabs defaultValue="login" className="w-full">
              <TabsList className="grid w-full grid-cols-2 mb-6">
                <TabsTrigger value="login" className="flex items-center space-x-2">
                  <LogIn className="h-4 w-4" />
                  <span>登录</span>
                </TabsTrigger>
                <TabsTrigger value="register" className="flex items-center space-x-2">
                  <UserPlus className="h-4 w-4" />
                  <span>注册</span>
                </TabsTrigger>
              </TabsList>

              {error && (
                <Alert className="mb-4 border-red-200 bg-red-50">
                  <AlertDescription className="text-red-700">
                    {error}
                  </AlertDescription>
                </Alert>
              )}

              {/* 登录表单 */}
              <TabsContent value="login">
                <form onSubmit={handleLogin} className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="login-account">账户名</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        id="login-account"
                        type="text"
                        placeholder="请输入账户名"
                        value={loginForm.userAccount}
                        onChange={(e) => setLoginForm({ ...loginForm, userAccount: e.target.value })}
                        className="pl-10"
                        disabled={loading}
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="login-password">密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        id="login-password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请输入密码"
                        value={loginForm.userPassword}
                        onChange={(e) => setLoginForm({ ...loginForm, userPassword: e.target.value })}
                        className="pl-10 pr-10"
                        disabled={loading}
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowPassword(!showPassword)}
                        disabled={loading}
                      >
                        {showPassword ? (
                          <EyeOff className="h-4 w-4 text-gray-400" />
                        ) : (
                          <Eye className="h-4 w-4 text-gray-400" />
                        )}
                      </Button>
                    </div>
                  </div>

                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700"
                    disabled={loading}
                  >
                    {loading ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        登录中...
                      </>
                    ) : (
                      <>
                        <LogIn className="h-4 w-4 mr-2" />
                        登录
                      </>
                    )}
                  </Button>
                </form>
              </TabsContent>

              {/* 注册表单 */}
              <TabsContent value="register">
                <form onSubmit={handleRegister} className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="register-account">账户名</Label>
                    <div className="relative">
                      <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        id="register-account"
                        type="text"
                        placeholder="请输入账户名"
                        value={registerForm.userAccount}
                        onChange={(e) => setRegisterForm({ ...registerForm, userAccount: e.target.value })}
                        className="pl-10"
                        disabled={loading}
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="register-password">密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        id="register-password"
                        type={showPassword ? "text" : "password"}
                        placeholder="请输入密码（至少6位）"
                        value={registerForm.userPassword}
                        onChange={(e) => setRegisterForm({ ...registerForm, userPassword: e.target.value })}
                        className="pl-10 pr-10"
                        disabled={loading}
                      />
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                        onClick={() => setShowPassword(!showPassword)}
                        disabled={loading}
                      >
                        {showPassword ? (
                          <EyeOff className="h-4 w-4 text-gray-400" />
                        ) : (
                          <Eye className="h-4 w-4 text-gray-400" />
                        )}
                      </Button>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="register-confirm">确认密码</Label>
                    <div className="relative">
                      <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                      <Input
                        id="register-confirm"
                        type="password"
                        placeholder="请再次输入密码"
                        value={registerForm.checkPassword}
                        onChange={(e) => setRegisterForm({ ...registerForm, checkPassword: e.target.value })}
                        className="pl-10"
                        disabled={loading}
                      />
                    </div>
                  </div>

                  <Button 
                    type="submit" 
                    className="w-full bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700"
                    disabled={loading}
                  >
                    {loading ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        注册中...
                      </>
                    ) : (
                      <>
                        <UserPlus className="h-4 w-4 mr-2" />
                        注册
                      </>
                    )}
                  </Button>
                </form>
              </TabsContent>
            </Tabs>

            {/* 演示账户提示 */}
            <div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
              <p className="text-sm text-blue-700 text-center">
                <strong>演示提示：</strong> 您可以注册新账户或使用演示数据进行体验
              </p>
            </div>
          </CardContent>
        </Card>

        {/* 底部信息 */}
        <div className="text-center mt-8 text-sm text-gray-500">
          <p>© 2025 智能BI平台. 保留所有权利.</p>
        </div>
      </div>
    </div>
  );
}